package com.jiazhong.cloud.gateway.example.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiazhong.cloud.commons.bean.Student;
import com.jiazhong.cloud.commons.config.JwtConfig;
import com.jiazhong.cloud.commons.util.JsonResult;
import com.jiazhong.cloud.commons.util.MD5Util;
import com.jiazhong.cloud.commons.util.ResultTool;
import com.jiazhong.cloud.gateway.example.auth.mapper.StudentMapper;
import com.jiazhong.cloud.gateway.example.auth.service.StudentService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    private StudentMapper studentMapper;
    private StringRedisTemplate stringRedisTemplate;
    private ValueOperations<String, String> valueOperations;

    @Autowired
    public StudentServiceImpl(StudentMapper studentMapper, StringRedisTemplate stringRedisTemplate) {
        this.studentMapper = studentMapper;
        this.stringRedisTemplate = stringRedisTemplate;
        valueOperations = stringRedisTemplate.opsForValue();
    }

    @Override
    public JsonResult login(Student student) {
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stu_no", student.getStuNo());
        queryWrapper.eq("password", MD5Util.encryptMD5(student.getPassword()));
        Student one = studentMapper.selectOne(queryWrapper);
        if (one == null) {
            return ResultTool.fail(500, "账号或者密码错误");
        }
        String token = JwtConfig.getJwtToken(one);
        valueOperations.set("token:" + one.getId(), token,1, TimeUnit.DAYS);
        return ResultTool.success(token);
    }
}
